import { defineConfig } from 'vite'
import { fileURLToPath, URL } from 'node:url'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    dedupe: ['react', 'react-dom'],
    alias: {
      // Some bundled libs expect a default export from this path
      'use-sync-external-store/shim/with-selector.js': fileURLToPath(new URL('./src/shims/with-selector-default.ts', import.meta.url)),
      'use-sync-external-store/shim/with-selector': fileURLToPath(new URL('./src/shims/with-selector-default.ts', import.meta.url))
    }
  },
  optimizeDeps: {
    exclude: ['three'],
    include: [
      'use-sync-external-store',
      'use-sync-external-store/shim/with-selector'
    ],
    esbuildOptions: {
      external: ['three']
    }
  },
  server: {
    proxy: {
      // 代理阿里云 TTS 接口，解决浏览器直连的 CORS 限制
      '/ali-tts': {
        target: 'https://nls-gateway-cn-shanghai.aliyuncs.com',
        changeOrigin: true,
        secure: true,
        rewrite: (path) => path.replace(/^\/ali-tts/, ''),
        configure: (proxy) => {
          // 允许转发二进制流
          proxy.on('proxyReq', (proxyReq) => {
            proxyReq.setHeader('Origin', 'https://nls-gateway-cn-shanghai.aliyuncs.com')
          })
        }
      }
    }
  }
})
